package za.org.jcicada.cfgmngr.impl;

import java.net.URI;

import za.org.jcicada.cfgmngr.ISystemObserver;
import za.org.jcicada.cfgmngr.ISystemSubject;
import za.org.jcicada.cfgmngr.messages.AttachReply;
import za.org.jcicada.cfgmngr.messages.AttachRequest;
import za.org.jcicada.cfgmngr.messages.DetachReply;
import za.org.jcicada.cfgmngr.messages.DetachRequest;
import za.org.jcicada.cfgmngr.messages.SystemEventInform;
import za.org.jcicada.comms.IConnector;
import za.org.jcicada.comms.impl.MessageListenerBase;
import za.org.jcicada.comms.impl.ProxyBase;

/**
 * IConfigurationSubject implementation that proxies requests through to a
 * remote configuration subject.
 * 
 * @author rcrida
 * 
 */
public class SystemSubjectProxy extends ProxyBase<ISystemObserver> implements ISystemSubject {

	public SystemSubjectProxy(IConnector connector) {
		super(connector);
	}
	
	public SystemSubjectProxy(URI locationURI) {
		super(locationURI);
	}

	@Override
	protected MessageListenerBase createReceiver(ISystemObserver client) {
		return new Receiver(client);
	}

	public void requestAttach(ISystemObserver observer) {
		sendMessage(observer, new AttachRequest());
	}

	public void requestDetach(ISystemObserver observer) {
		sendMessage(observer, new DetachRequest());
	}

	/**
	 * Implementation of IMessageListener that dispatches messages to an
	 * IConfigurationObserver.
	 */
	public class Receiver extends MessageListenerBase {
		
		/**
		 * Handle to callback object for messages from teh subject to the
		 * client.
		 */
		ISystemObserver observer;
		
		public Receiver(ISystemObserver observer) {
			this.observer = observer;
		}
		
		public void onClose() throws Exception {
			observer.informDisconnect();
		}
		
		// dispatch methods
		
		public void cfgmngrAttachReply(AttachReply msg) {
			observer.replyAttach(msg.getResult());
		}
		
		public void cfgmngrDetachReply(DetachReply msg) {
			observer.replyDetach(msg.getResult());
		}
		
		public void cfgmngrSystemEventInform(SystemEventInform msg) {
			observer.informSystemEvent(msg.getSystemURN(), msg.getSystemSetType(), msg.getEvent());
		}
	}

}
